<template>
  <div class="user-management">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="用户名">
          <el-input
            v-model="filterForm.username"
            placeholder="请输入用户名"
            clearable
            @clear="handleFilter"
            @keyup.enter="handleFilter"
          />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input
            v-model="filterForm.realName"
            placeholder="请输入真实姓名"
            clearable
            @clear="handleFilter"
            @keyup.enter="handleFilter"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            clearable
            @change="handleFilter"
          >
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="暂停" value="suspended" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="filterForm.roleId"
            placeholder="选择角色"
            clearable
            @change="handleFilter"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="user-table-card">
      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="department" label="院系" width="120" />
        <el-table-column prop="classInfo" label="班级" width="120" />
        <el-table-column label="角色" width="150">
          <template #default="scope">
            <el-tag
              v-for="role in scope.row.roles"
              :key="role.id"
              size="small"
              style="margin-right: 4px"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="warning"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.status === "active" ? "禁用" : "启用" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPassword"
          v-if="!editingUser"
        >
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="院系">
          <el-input v-model="userForm.department" placeholder="请输入院系" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="userForm.classInfo" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="userForm.roleIds"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitUserForm"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import request from "@/utils/request";



// 响应式数据
const userList = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);
const tableHeight = ref(600);

const showCreateDialog = ref(false);
const editingUser = ref(null);
const submitLoading = ref(false);
const userFormRef = ref();

const filterForm = reactive({
  username: "",
  realName: "",
  status: "",
  roleId: "",
});

const userForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
  phone: "",
  realName: "",
  department: "",
  classInfo: "",
  roleIds: [],
  status: "active",
});

const roles = ref([
  { id: 1, name: "管理员" },
  { id: 2, name: "教师" },
  { id: 3, name: "学生" },
  { id: 4, name: "志愿者" },
]);

const userRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在3到20个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== userForm.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
};

// 模拟数据
const mockUsers = [
  {
    id: 1,
    username: "admin",
    realName: "系统管理员",
    email: "admin@example.com",
    phone: "13800138000",
    department: "信息学院",
    classInfo: "",
    roles: [{ id: 1, name: "管理员" }],
    status: "active",
    createdAt: "2025-01-01 10:00:00",
  },
  {
    id: 2,
    username: "teacher1",
    realName: "张老师",
    email: "teacher1@example.com",
    phone: "13800138001",
    department: "医学院",
    classInfo: "",
    roles: [{ id: 2, name: "教师" }],
    status: "active",
    createdAt: "2025-01-02 10:00:00",
  },
  {
    id: 3,
    username: "student1",
    realName: "李明",
    email: "student1@example.com",
    phone: "13800138002",
    department: "信息学院",
    classInfo: "计算机专业2021级",
    roles: [{ id: 3, name: "学生" }],
    status: "active",
    createdAt: "2025-01-03 10:00:00",
  },
];

const dialogTitle = computed(() => {
  return editingUser.value ? "编辑用户" : "新增用户";
});

const loadUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      username: filterForm.username || undefined,
      realName: filterForm.realName || undefined,
      status: filterForm.status || undefined,
      roleId: filterForm.roleId || undefined,
    };

    const response = await request.get("/api/users", params);

    if (response.success) {
      userList.value = response.data;
      total.value = response.pagination.total;
    } else {
      ElMessage.error(response.message || "加载用户列表失败");
    }
  } catch (error) {
    console.error("加载用户列表失败:", error);
    ElMessage.error("加载用户列表失败");
  } finally {
    loading.value = false;
  }
};

const handleFilter = () => {
  currentPage.value = 1;
  loadUsers();
};

const resetFilter = () => {
  Object.keys(filterForm).forEach((key) => {
    filterForm[key] = "";
  });
  handleFilter();
};

const getStatusType = (status: string) => {
  const types = {
    active: "success",
    inactive: "danger",
    suspended: "warning",
  };
  return types[status as keyof typeof types] || "info";
};

const getStatusText = (status: string) => {
  const texts = {
    active: "正常",
    inactive: "禁用",
    suspended: "暂停",
  };
  return texts[status as keyof typeof texts] || status;
};

const editUser = (user: any) => {
  editingUser.value = user;
  Object.assign(userForm, {
    username: user.username,
    password: "",
    confirmPassword: "",
    email: user.email,
    phone: user.phone,
    realName: user.realName,
    department: user.department,
    classInfo: user.classInfo,
    roleIds: user.roles.map((r: any) => r.id),
    status: user.status,
  });
  showCreateDialog.value = true;
};

const toggleUserStatus = async (user: any) => {
  try {
    const newStatus = user.status === "active" ? "inactive" : "active";

    const response = await request.patch(`/api/users/${user.id}/status`, {
      status: newStatus,
    });

    if (response.success) {
      user.status = newStatus;
      ElMessage.success("操作成功");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("更新用户状态失败:", error);
    ElMessage.error("操作失败");
  }
};

const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await request.delete(`/api/users/${user.id}`);

    if (response.success) {
      loadUsers();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    console.log("取消删除");
  }
};

const submitUserForm = async () => {
  if (!userFormRef.value) return;

  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        const submitData = {
          username: userForm.username,
          password: userForm.password,
          email: userForm.email,
          phone: userForm.phone,
          realName: userForm.realName,
          department: userForm.department,
          classInfo: userForm.classInfo,
          roleIds: userForm.roleIds,
        };

        let response;
        if (editingUser.value) {
          // 编辑用户
          response = await request.put(`/api/users/${editingUser.value.id}`, {
            email: userForm.email,
            phone: userForm.phone,
            realName: userForm.realName,
            department: userForm.department,
            classInfo: userForm.classInfo,
            roleIds: userForm.roleIds,
          });
        } else {
          // 新增用户
          response = await request.post("/api/users", submitData);
        }

        if (response.success) {
          showCreateDialog.value = false;
          resetUserForm();
          loadUsers();
          ElMessage.success("操作成功");
        } else {
          ElMessage.error(response.message || "操作失败");
        }
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetUserForm = () => {
  editingUser.value = null;
  Object.assign(userForm, {
    username: "",
    password: "",
    confirmPassword: "",
    email: "",
    phone: "",
    realName: "",
    department: "",
    classInfo: "",
    roleIds: [],
    status: "active",
  });
  userFormRef.value?.clearValidate();
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadUsers();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadUsers();
};

// 初始化加载
onMounted(() => {
  loadUsers();
});

// 监听对话框关闭重置表单
watch(showCreateDialog, (newVal) => {
  if (!newVal) {
    resetUserForm();
  }
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.user-table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
